package com.googlecode.gaal.analysis.impl;

import java.util.Iterator;

import com.googlecode.gaal.analysis.api.Filter;
import com.googlecode.gaal.data.api.IntSequence;
import com.googlecode.gaal.suffix.api.EmbeddedSuffixTree.EmbeddedInterval;
import com.googlecode.gaal.suffix.api.IntervalTree.Interval;

public class SimpleContextFilter implements Filter<EmbeddedInterval> {
    private final double minLeftRightContextRatio;
    private final int minNonEmptyFillerCount;

    public SimpleContextFilter(double minLeftRightContextRatio, int minNonEmptyFillerCount) {
        this.minLeftRightContextRatio = minLeftRightContextRatio;
        this.minNonEmptyFillerCount = minNonEmptyFillerCount;
    }

    @Override
    public boolean passed(EmbeddedInterval embeddedInterval) {
        Interval interval = embeddedInterval.getEmbeddingInterval();
        double leftRightContextRatio = (double) embeddedInterval.size() / interval.size();
        int nonEmptyFillerCount = 0;
        int prevPrefix = -1;
        boolean hasCommonPrefix = true; // all the fillers share a common
                                        // prefix
        int prevSuffix = -1;
        boolean hasCommonSuffix = true; // all the fillers share a common
                                        // suffix
        Iterator<IntSequence> fillerIterator = embeddedInterval.fillerIterator();
        while (fillerIterator.hasNext()) {
            IntSequence filler =  fillerIterator.next();
            if (prevPrefix != -1 && hasCommonPrefix && (filler.size() == 0 || filler.get(0) != prevPrefix)) {
                hasCommonPrefix = false;
            }
            if (prevSuffix != -1 && hasCommonSuffix
                    && (filler.size() == 0 || filler.get(filler.size() - 1) != prevSuffix)) {
                hasCommonSuffix = false;
            }
            if (filler.size() > 0) {
                prevPrefix = filler.get(0);
                prevSuffix = filler.get(filler.size() - 1);
                nonEmptyFillerCount++;
            }
        }
        return (!hasCommonPrefix && !hasCommonSuffix && leftRightContextRatio > minLeftRightContextRatio && nonEmptyFillerCount > minNonEmptyFillerCount);
    }
}
